package com.jacky.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class  MyHandler implements InvocationHandler {
    private Object object = null;

    /**
     *
     * @param object 被代理类对象
     * @param <T>
     * @return
     */
    public <T> T getInstance(T object){
        this.object = object;
        final Class<?> clazz = object.getClass();
        // proxyInstance的Class类是$Proxy0,这个$Proxy0类继承了Proxy，实现了clazz.getInterfaces()接口
        final Object proxyInstance = Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), clazz.getInterfaces(), this);
        return (T) proxyInstance;
    }

    /**
     *
     * @param proxy 在invoke中被赋值为this，而this就是代理实例
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("\n-----华丽的分割线1-----");
        System.out.println(proxy.getClass().getName());
        System.out.println(this);
        System.out.println("this.getClass:"+this.getClass());
        System.out.println(super.getClass());

        System.out.println("\n-----华丽的分割线2-----");
        System.out.println(Thread.currentThread().getStackTrace()[1]);
        System.out.println(Thread.currentThread().getStackTrace()[2]);
        System.out.println(Thread.currentThread().getStackTrace()[3]);
        System.out.println(Thread.currentThread().getStackTrace()[4]);

        System.out.println("**********pre**********");
        final Object invoke = method.invoke(object, args);
        System.out.println("**********post**********");
        return invoke;
    }
}
